<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/12/4
 * Time: 10:16
 */

namespace app\api\controller;


use think\Db;

class Sign extends Base
{
    private $user_id;
    private $page;
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 用户签到
     * @return \think\response\Json
     */
    public function userSign(){
        if($this->user_id == 0) return json(['status' => 0, 'msg' => '请先登录']);
        $district = input('district');
        /*
         * 每天签到查找上一次签到日期，
         * 是否是连续签到，如果连续签到，则连续签到日期天数+1，累计连续天数+1
         * 如果不是连续签到，则连续签到天数置1，累计连续天数置1
         * */
        // 获取上一天日期
        $last_date = date('Y-m-d', strtotime('-1 day'));
        // 获取当天日期/月份/日
        $date = date('Y-m-d');
        $month = date('Y-m');
        $day = date('d');
        // 该用户最近的一条签到记录
        $have = $this->userSign_info();
        $sign_days = 1; // 连续签到天数
        $sign_total_days = 1; // 累计连续签到天数
        // 连续签到天数和奖励
        $have_award = Db::table('up_sign_draw')->where('sd_id', 1)->field('sd_draw_num, sd_sign_num')->find();
        if($have){
            if(strtotime($have['sign_date']) == strtotime($date)){
                return json(['status' => 0, 'msg' => '今日已签到']);
            }
            // 连续签到
            if(strtotime($have['sign_date']) == strtotime($last_date)){
                // 如果昨天已经拿到奖励，则今日重新计算
                if($have['sign_days'] != $have_award['sd_sign_num']){
                    $sign_days = $have['sign_days'] + 1;
                }
                $sign_total_days = $have['sign_total_days'] + 1;
            }
        }
        // 查看是否有签到奖励
//        $have_award = Db::table('up_sign_draw')->where('sd_sign_num', $sign_days)->field('sd_draw_num')->find();
        Db::startTrans();
        try{
            // 更新签到表
            $sign = [
                'sign_user_id' => $this->user_id,
                'sign_date' => $date,
                'sign_datetime' => $this->create_time,
                'sign_month' => $month,
                'sign_day' => ltrim($day, '0'),
                'sign_days' => $sign_days,
                'sign_total_days' => $sign_total_days,
                'sign_district' => $district,
            ];
            Db::table('up_user_sign')->insert($sign);
            // 如果今日连续签到天数等于设置的连续签到奖励天数，则发放奖励
            if($sign_days == $have_award['sd_sign_num']){
                $draw_info = [
                    'info_user_id' => $this->user_id,
                    'info_draw_times' => $have_award['sd_draw_num'],
                    'info_times_desc' => '连续签到' . $sign_days . '天',
                    'info_times_type' => 1,
                    'info_time' => $this->create_time,
                    'info_district' => $district
                ];
                Db::table('up_draw_info')->insert($draw_info);
                Db::table('up_u_user')->where('user_id', $this->user_id)->setInc('user_draw_times', $have_award['sd_draw_num']);
            }
            Db::commit();
            return json(['status' => 200, 'msg' => '签到成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 签到页面信息
     * @return \think\response\Json
     * month      月份   2020-01 格式
     */
    public function signInfo(){
        $month = input('month'); // 月份  格式2020-01 如果没有，则获取当前年月
        if($month == ''){
            $month = date('Y-m');
        }
        $date = date('Y-m-d');
        // 本月的签到日期
        $sign_day = Db::table('up_user_sign')
            ->where('sign_month', $month)
            ->where('sign_user_id', $this->user_id)
            ->column('sign_day');
        // 连续签到天数
        $sign_times = Db::table('up_user_sign')
            ->where('sign_user_id', $this->user_id)
            ->order('sign_datetime desc')
            ->value('sign_total_days');
//            ->field('sign_days, sign_total_days')
//            ->find();
        // 剩余抽奖次数
        $draw_times = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->value('user_draw_times');
        // 今日是否已签到
        $is_sign = Db::table('up_user_sign')
            ->where('sign_user_id', $this->user_id)
            ->where('sign_date', $date)
            ->find();
        if($is_sign){
            $today_sign = 1; // 今日已签到
        }else{
            $today_sign = 2; // 今日未签到
        }
       
        /*
         * https://hd.so37.com/dzp/lottery/rotate/index.php?lid=3&u=2fbd144ce4cf673acddc0375548c6941&act=addnum&add=2
         * u            加密参数
         * act=addnum   增加抽奖（固定不变）
         * add          增加的次数（可抽奖次数）
         * */
        $userid = $this->user_id . '|ckuid|';
//        $aeskey = 'aes128';
        $data = openssl_encrypt($userid, 'AES-128-ECB', $this->aeskey, OPENSSL_RAW_DATA);
        $u = strtolower(bin2hex($data));
//        $url = 'http://new4.xuanwumobile.com/choujiang/lottery/rotate/index.php?lid=1&u=' . $u . '&act=addnum&add=' . $draw_times;
        $url = 'http://ctruckapp1.ctruck.com.cn/choujiang/lottery/rotate/index.php?lid=1&u=' . $u . '&act=addnum&add=' . $draw_times;
        
        return json([
            'status' => 200,
            'msg' => '',
            'sign_day' => $sign_day,
            'sign_times' => $sign_times,
            'draw_times' => $draw_times,
            'today_sign' => $today_sign,
            'url' => $url
        ]);
    }
    
    /**
     * 兑换记录
     * @return \think\response\Json
     * page    页码
     */
    public function dhRecord(){
        $record = Db::table('up_draw_info')
            ->where('info_user_id', $this->user_id)
            ->field('info_draw_times, info_times_desc, info_times_type, info_time')
            ->page($this->page, 10)
            ->order('info_time desc')
            ->select();
        if($record){
            return json(['status' => 200, 'msg' => $record]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 签到规则
     * @return \think\response\Json
     */
    public function signRule(){
        $rule = Db::table('up_about')->where('about_id', 104)->value('about_content');
        return json(['status' => 200, 'msg' => $rule]);
    }
    
    /**
     * 该用户最近一次签到记录
     * @return array|false|\PDOStatement|string|\think\Model
     */
    private function userSign_info(){
        $have = Db::table('up_user_sign')
            ->where('sign_user_id', $this->user_id)
            ->field('sign_id, sign_days, sign_total_days, sign_date')
            ->order('sign_date desc')
            ->find();
        return $have;
    }
}